# -*- coding: utf-8 -*-

# @Time : 2022/6/12 16:27

# @Author : scy

# @File : __init__.py.py

# @Software: PyCharm

import pymysql


class interactSql:
    # 初始化函数
    def __init__(self, host='localhost', user='root', password='scy1401957592', database='soul'):
        # 不使用的话跳过
        self.__cursor = None
        self.__connect = None
        if host == '' or user == '' or password == '' or database == '':
            return
        # 修改连接属性
        self.__connect_host = host
        self.__connect_user = user
        self.__connect_password = password
        self.__connect_database = database

    # 修改host
    def set_host(self, new_host):
        self.__connect_host = new_host

    # 获取host
    def get_host(self):
        return self.__connect_host

    # 修改user
    def set_user(self, new_user):
        self.__connect_user = new_user

    # 获取user
    def get_user(self):
        return self.__connect_user

    # 修改密码
    def set_password(self, new_password):
        self.__connect_password = new_password

    # 获取password
    def get_password(self):
        return self.__connect_password

    # 修改数据库
    def set_database(self, new_database):
        self.__connect_database = new_database

    # 获取数据库
    def get_database(self):
        return self.__connect_database

    # 连接数据
    def connect_sql(self):
        self.__connect = pymysql.connect(host=self.__connect_host, user=self.__connect_user,
                                         password=self.__connect_password, database=self.__connect_database,
                                         charset='utf8')

    # 返回连接
    def get_connect(self):
        return self.__connect

    # 生成游标
    def cursor_sql(self):
        self.__cursor = self.__connect.cursor()

    # 获取游标
    def get_cursor(self):
        return self.__cursor

    # 查询表信息
    def inquire_table(self, table_name):
        return self.__cursor.execute('select * from %s' % (table_name))

    # 获取游标查询结果
    def get_results(self, result_sum=0):
        if result_sum == 0:
            return self.__cursor.fetchall()
        else:
            return self.__cursor.fetchmany(result_sum)

    # 运行是sql语句
    def run_sql(self, sql_statement):
        self.__cursor.execute(sql_statement)

    # 运行sql联合语句
    def run_union_s1l(self, sql_statement, date_list):
        self.__cursor.executemany(sql_statement, date_list)

    # 关闭数据库
    def close_database(self, close_traget):
        if close_traget == 'connect':
            self.__connect.close()
        else:
            self.__cursor.close()

    # 提交数据
    def commit(self):
        self.__connect.commit()

    # 回滚数据
    def rollback(self):
        self.__connect.rollback()
